package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 更新用户头像
     * @param headPhoto
     * @param id
     */
    // public void updateHead(MultipartFile headPhoto, Integer id) throws IOException {
     public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        // 1. 将图片上传到阿里云OSS
        // String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // !!! 阿里云OSS收费, 这里暂时跳过
        String imageUrl = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202108%2F28%2F20210828122250_3b289.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002";

        // 2. 调用百度云判断图片是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);

        // 3. 如果不包含人脸,抛出异常
        if(!detect) {
            // throw new RuntimeException("图片不正确");
             throw new BusinessException(ErrorResult.faceError());
        // 4. 如果包含人脸,调用aip更新
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    /**
     * 根据id查询
     * @param id
     */
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);
        UserInfoVo vo = new UserInfoVo();

        // vo.setId(userInfo.getId());
        // vo.setNickname(userInfo.getNickname());
        // ...
        BeanUtils.copyProperties(userInfo, vo); // 只会copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    /**
     * 更新用户资料
     * @param userInfo
     */
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
